package com.boot.service;

import com.boot.entity.Menu;
import com.boot.entity.User;
import com.boot.mapper.UserMapper;
import com.boot.vo.AuthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public List<User> list(Integer current,Integer pageSize){
        if(current ==null){
            current = 1;
        }

        if(pageSize == null){
            pageSize = 10;
        }

        Integer start = (current - 1) * pageSize;

        return userMapper.list(start,pageSize,null);
    }


    public Map<String,Object> page(Integer current,Integer pageSize,String userName){
        if(current ==null || current < 1){
            current = 1;
        }

        if(pageSize == null || pageSize < 1){
            pageSize = 10;
        }

        Integer start = (current - 1) * pageSize;

        List<User> users = userMapper.list(start,pageSize,userName);

        int count = userMapper.count(userName);
        int pages = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        Map<String,Object> map = new HashMap<>();
        map.put("users",users);

        map.put("pages",pages);

        return map;
    }

    public void del(Long id) {
        userMapper.del(id);
    }

    public User getById(Long id) {
        return userMapper.getById(id);
    }

    public void saveOrUpdate(User user) {
        if(user.getId()==null){
            //保存
            userMapper.save(user);
        }else{
            userMapper.updateById(user);
        }
    }

    public void delByIds(List<Long> ids) {
        userMapper.delByIds(ids);
    }

    public User login(String userName, String password) {
        User user = userMapper.selectByUserNameAndPassword(userName,password);
        return user;
    }

    public void auth(AuthVo authVo) {
        userMapper.delAuth(authVo.getUserId());
        userMapper.auth(authVo);
    }

    public List<Menu> getMenusByUserId(Long id) {
        return userMapper.getMenusByUserId(id);
    }
}
